const maxHaibaoSubstring = 5
$(document).ready(() => {
  // 切换时清空推荐理由
  $(`x-tuijian #tuijian`).on('change', (evt) => {
    $(evt.target).siblings(`input[type='text']`).val(null)
  })

  // 自动选择一个海报的名字
  $(`x-haibao #tuiguang_name_3`).prop('checked', true).change()
  // 自定义名称
  $(`x-haibao #tuiguang_name_5`).siblings(`input[type='text']`).on('click', (evt) => {
    $(evt.target).siblings(`input[type='radio']`).prop('checked', true)
  })
  $(`x-haibao #tuiguang_name_5`).siblings(`input[type='text']`).on('keyup', (evt) => {
    $(evt.target).siblings(`input[type='radio']`).prop('checked', true)
    $(evt.target).change()
  })
  $(`x-haibao #tuiguang_name_5`).siblings(`input[type='text']`).on('change', (evt) => {
    const content = String($(evt.target).val()).substring(0, maxHaibaoSubstring)
    $(`x-haibao .haibao_img .haibao_pro_name`).text(content)
  })
  // 留空时自动填入  自定义名字 五字
  $(`x-haibao #tuiguang_name_5`).siblings(`input[type='text']`).on('blur', (evt) => {
    if (String($(evt.target).val()).replace(/[\s　]/g, '') === '') {
      $(evt.target).val('预定义名称').change()
    }
  })

  // 动态修改海报文字
  // 真实名称
  $(`x-haibao #tuiguang_name_1`).closest('label').on('click', (evt) => {
    const content = String($(`input[name='litter_name']`).val()).substring(0, maxHaibaoSubstring)
    if (content === '') {
      evt.stopPropagation()
      evt.preventDefault()
      alert('请先填写产品小名')
      $(`input[name='litter_name']`).focus()
      throw new Error(`无法获取产品小名`)
    }
    $(`x-haibao .haibao_img .haibao_pro_name`).text(content)
  })
  // 自定义名称
  $(`x-haibao #tuiguang_name_2`).closest('label').on('click', (evt) => {
    $(`x-haibao .haibao_img .haibao_pro_name`).text('自定义名称')
  })
  // 不显示名称
  $(`x-haibao #tuiguang_name_3`).closest('label').on('click', (evt) => {
    $(`x-haibao .haibao_img .haibao_pro_name`).text(null)
  })
  // 预定义名称
  $(`x-haibao #tuiguang_name_5`).closest('label').on('click', (evt) => {
    const content = String($(`x-haibao #tuiguang_name_5`).siblings(`input[type='text']`).val()).substring(0, 8)
    if (content === '') {
      $(`x-haibao #tuiguang_name_5`).siblings(`input[type='text']`).val('预定义名称').change()
    }
    $(`x-haibao #tuiguang_name_5`).siblings(`input[type='text']`).change()
  })
  $(`x-haibao #tuiguang_edu_miaosu`).on('keyup', (evt) => {
    const content = String($(evt.target).val()).substring(0, maxHaibaoSubstring)
    $(`x-haibao .haibao_img .lixi_content`).text(content)
    //
  })
  $(`x-haibao #tuiguang_adv_miaosu`).on('keyup', (evt) => {
    const content = String($(evt.target).val()).substring(0, maxHaibaoSubstring)
    $(`x-haibao .haibao_img .adv_content`).text(content)
    //
  })
})

function submitADnHaibao () {
  let AjaxURL
  const AjaxAddURL = String($('#post_ajax_add_goods_ad').val())
  const AjaxUpdataURL = String($('#post_ajax_update_goods_ad').val())
  let nameState = $(`x-haibao input[name='tuiguang_chanpin']:checked`).val()
  let specialName = String($(`x-haibao input[name='tuiguang_chanpin_zidingyi']`).val())
  let ajaxData = {
    // 单选处理0真实名称1商家定义2不显示名称3自定义名称
    goods_name_state: nameState,
    // 利息额度描述
    lx_ed_dep: String($(`x-haibao #tuiguang_adv_miaosu`).val()),
    // 优势描述
    adv_dep: String($(`x-haibao #tuiguang_edu_miaosu`).val()),
    // 商品gid
    g_id: location.href.match(/\/id\/(\d+)/)[1],
    // 商品名称
    goods_name: specialName,
    ad_img: $(`.haibao_wrap img`).attr('src')
  }
  if (String($(`#x_haibao_id`).val()) !== 'null') {
    AjaxURL = AjaxUpdataURL
    ajaxData.goods_ad_id = $(`#x_haibao_id`).val()
  } else {
    AjaxURL = AjaxAddURL
  }
  $.ajax(AjaxURL, {
    method: 'post',
    data: ajaxData
  }).fail((err) => {
    alert(`通信失败，请重试`)
    throw err
  }).done((res) => {
    const resData = res.data
    let flag = String(res.code) === '2'
    if (flag && String(typeof res.data).toLowerCase() === 'array') {
      $.each(res.data, (index, item) => {
        if (String(item) === 'false') flag = false
      })
    }
    if (String(res.code) === '1' || flag) {
      $(`#x_haibao_id`).val(res.goods_ad_id)
    } else {
      layer.msg(`提交推广数据失败，服务器返回：${res.data}`)
    }
  })
}

// 提交推荐选项
function submitTuijian () {
  const ID = String($('#x-tuijian-id').val())
  const addURL = String($('#post_ajax_add_goods_diy_name').val())
  const updateURL = String($('#post_ajax_update_goods_diy_name').val())
  let AjaxURL = ``
  let AjaxData = {
    g_id: location.href.match(/\/id\/(\d+)/)[1],
    state: String($(`x-tuijian input[type='checkbox']`).prop('checked')) === 'true' ? 1 : 0, // true
    goods_name_reason: $(`x-tuijian input[name='tuijian_reason']`).val()
  }
  if (ID === 'null') {
    AjaxURL = addURL
  } else {
    AjaxURL = updateURL
    AjaxData.goods_diy_name_id = ID
  }
  $.ajax(AjaxURL, {
    method: 'post',
    data: AjaxData,
    beforeSend: () => {
      layer.msg(`正在发送推荐信息`)
    }
  }).fail((err) => {
    throw err
  }).done((res) => {
    if (String(res.code) === '1' || (String(res.code) === '2' && String(res.data) !== 'false')) {
      if (res.goods_diy_name_id !== undefined) {
        $(`#x-tuijian-id`).val(`${res.goods_diy_name_id}`)
      }
    } else {
      layer.msg(`推荐消息发送失败，请重试`)
      throw new Error(`推荐消息发送失败：${res.message}`)
    }
  })
}

$(document).ready(() => {
  /*

    let altFormDataZhengxin = `[{"cinv_times_id":"15","zhengxin_check_if":"1","zhengxin_check_count_method":"\u4e2a\u4eba\u67e5\u8be2","zhengxin_check_count_cycle":"1","zhengxin_check_count_time":"18","cinv_times_color":"#000","g_id":"30","state":"1"}]`;
    let altFormDataZhengxiYuqi = `[{"cinv_see_id":"14","yuqi_check_if":"1","yuqi_check_count_cycle":"1","yuqi_check_count_method":"\u7d2f\u8ba1","yuqi_check_count_time":"2","yuqi_check_count_source":"3","g_id":"30","state":"1","cinv_see_color":"#000"}]`;
    let altformDataHaibao = `[{"goods_ad_id":"7","goods_name_state":"2","lx_ed_dep":"","adv_dep":"","time":"2018\u5e7401\u670823\u65e5 04:58:54","g_id":"30","ad_img":"https:\/\/ss0.bdstatic.com\/94oJfD_bAAcT8t7mm9GUKT-xh_\/timg?image&quality=100&size=b4000_4000&sec=1516530300&di=ab46c4aa763445f2366af83938b4cbb8&src=http:\/\/image.tianjimedia.com\/uploadImages\/2015\/209\/42\/6H182F668EP9.jpg","u_id":"3","goods_name":""}]`;
    // [3]是关联，后端自己渲染
    let altformDataTuijian = `[{"goods_diy_name_id":"7","g_id":"30","u_id":null,"state":"0","goods_name_reason":""}]`;
    window.altFormData = {
      altFormDataZhengxin: altFormDataZhengxin,
      altformDataHaibao: altformDataHaibao,
      altformDataTuijian: altformDataTuijian,
      altFormDataZhengxiYuqi: altFormDataZhengxiYuqi
    }

  */
  /* 推荐选项数据 */
  let altformDataTuijian = window.altFormData.altformDataTuijian
  if (altformDataTuijian === '') {
    throw new Error(`停止推荐选项回填，不存在回填数据`)
  }
  try {
    altformDataTuijian = JSON.parse(`${altformDataTuijian}`)[0]
  } catch (err) {
    alert(`停止推荐选项回填，回填数据格式有误`)
    throw err
  }
  // 回填推荐数据
  if (altformDataTuijian.state === '1') $(`#tuijian`).click().prop('checked', true).change()
  $(`input[name='tuijian_reason']`).val(altformDataTuijian.goods_name_reason || '')
  $(`#x-tuijian-id`).val(altformDataTuijian.goods_diy_name_id)
  /* 海报数据 */
  let altformDataHaibao = window.altFormData.altformDataHaibao
  if (altformDataTuijian === '') {
    throw new Error(`停止海报数据回填，不存在回填数据`)
  }
  try {
    altformDataHaibao = JSON.parse(`${altformDataHaibao}`)[0]
  } catch (err) {
    alert(`停止海报数据回填，回填数据格式有误`)
    throw err
  }
  // 回填海报数据
  $(`x-haibao img`).attr('src', altformDataHaibao.ad_img)
  $(`x-haibao input[name='tuiguang_chanpin_zidingyi']`).val(altformDataHaibao.goods_name || '').keyup().change()
  $(`x-haibao input[type='radio'][value='${altformDataHaibao.goods_name_state}']`).prop('checked', true).change()
  $(`x-haibao #tuiguang_edu_miaosu`).val(altformDataHaibao.lx_ed_dep || '').keyup().change()
  $(`x-haibao #tuiguang_adv_miaosu`).val(altformDataHaibao.adv_dep || '').keyup().change()
  $(`#x_haibao_id`).val(altformDataHaibao.goods_ad_id)
})
